package top.lingkang.acgv.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpException;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.lingkang.acgv.acr.dto.ResponseResult;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

@RestController
@RequestMapping("/auth")
public class AuthController {

    @Value("${server.port}")
    private String port;

    @Autowired
    private TokenStore tokenStore;


    @RequestMapping(value = "/login")
    public Object login(String username, String password) {
        if (StrUtil.isBlank(username)) {
            return new ResponseResult<>().fail("账号不能为空！");
        }
        if (StrUtil.isBlank(password)) {
            return new ResponseResult<>().fail("密码不能为空！");
        }
        HashMap<String, String> json = new HashMap<>();
        json.put("username", username);
        json.put("password", password);
        json.put("client_id", "client");
        json.put("client_secret", "secret");
        json.put("grant_type", "password");
        //POST请求
        try {
            String res = HttpRequest.post("http://localhost:" + port + "/oauth/token")
                    .timeout(5000)//超时，毫秒
                    .formStr(json)
                    .execute().body();
            JSONObject parse = (JSONObject) JSONObject.parse(res);
            if (parse.containsKey("code") && parse.getInteger("code") != 0) {
                return new ResponseResult<>().fail(parse.getString("message"));
            }
            return new ResponseResult<>().success("登录成功", parse);
        } catch (Exception e) {
            return new ResponseResult<>().fail("登录失败", e.getMessage());
        }
    }

    @RequestMapping("refreshToken")
    public Object refreshToken(HttpServletRequest request) {
        HashMap<String, String> json = new HashMap<>();
        json.put("refresh_token", request.getParameter("refresh_token"));
        json.put("client_id", "client");
        json.put("client_secret", "secret");
        json.put("grant_type", "refresh_token");
        try {
            String res = HttpRequest.post("http://localhost:" + port + "/oauth/token")
                    .timeout(5000)//超时，毫秒
                    .formStr(json)
                    .execute().body();
            JSONObject parse = (JSONObject) JSONObject.parse(res);
            if (parse.containsKey("code") && parse.getInteger("code") != 0) {
                return new ResponseResult<>().fail(parse.getString("message"));
            }
            return new ResponseResult<>().success("刷新成功", parse);
        } catch (HttpException e) {
            return new ResponseResult<>().fail("刷新失败", e.getMessage());
        }
    }


    @GetMapping(value = "logout")
    public Object logout(HttpServletRequest request) {
        // 获取 token
        String token = request.getParameter("access_token");
        if (token == null) {
            token = request.getHeader("authorization");
            if (token != null)
                token = token.split(" ")[1];
        }
        OAuth2AccessToken accessToken = tokenStore.readAccessToken(token);
        if (accessToken != null) {
            if (accessToken.getRefreshToken() != null) {
                tokenStore.removeRefreshToken(accessToken.getRefreshToken());
            }
            tokenStore.removeAccessToken(accessToken);
        } else {
            return new ResponseResult<>().fail("无效的token！");
        }
        return new ResponseResult<>().success("注销成功！");
    }
}
